'use strict';

var usernamePage = document.querySelector('#username-page');
var chatPage = document.querySelector('#chat-page');
var usernameForm = document.querySelector('#usernameForm');
var messageForm = document.querySelector('#messageForm');
var messageInput = document.querySelector('#message');
var messageArea = document.querySelector('#messageArea');
var connectingElement = document.querySelector('.connecting');

var stompClient = null;
var username = null;

var colors = [
    '#2196F3', '#32c787', '#00BCD4', '#ff5652',
    '#ffc107', '#ff85af', '#FF9800', '#39bbb0'
];

function connect(event) {
    username = document.querySelector('#name').value.trim();

    if(username) {
        usernamePage.classList.add('hidden');
        chatPage.classList.remove('hidden');

        //连接后端服务暴露的节点
        var socket = new SockJS('/ws/chatroom');
        stompClient = Stomp.over(socket);

        stompClient.connect({
            username:username //携带参数（唯一识别值）

        }, onConnected, onError);
    }
    event.preventDefault();
}


function onConnected() {

    //额外订阅了mike频道,暂时当做自己的频道,别人需要特意往这个频道发送消息,才能完成 ‘单对单’
    stompClient.subscribe('/user/topic/touser', onMessageReceived)

    //订阅群发和单发主题
    // Subscribe to the Public Topic
    stompClient.subscribe('/topic/chatroom', onMessageReceived);

    stompClient.subscribe('/chatroom/sendtotest', onMessageReceived);

    // Tell your username to the server
    stompClient.send("/chatroom/addUser",
        {},
        JSON.stringify({
            fromId: '23',
            fromName: username,
            toId: '-1',
            toName: 'all',
            messageTypeId: '1',
            createTime: new Date()
        })
    )

    connectingElement.classList.add('hidden');
}


function onError(error) {
    connectingElement.textContent = 'Could not connect to WebSocket server. Please refresh this page to try again!';
    connectingElement.style.color = 'red';
}


function sendMessage(event) {
    var messageContent = messageInput.value.trim();

    if(messageContent && stompClient) {
        var chatMessage = {
            fromId: '23',
            fromName: username,
            toId: '-1',
            toName: 'all',
            messageTypeId: '2',
            content: messageContent,
            createTime: new Date()
        };
        stompClient.send("/chatroom/sendMessageTest", {}, JSON.stringify(chatMessage));
        //"/lucien/chat.sendMessageTest" 需要与 接口 @MessageMapping("/chat.sendMessageTest") 对应
        messageInput.value = '';
    }
    event.preventDefault();
}


function onMessageReceived(payload) {
    console.log(payload);
    var message = JSON.parse(payload.body);
    console.log(message);
    var messageElement = document.createElement('li');

    if(message.messageTypeId === 1) {
        messageElement.classList.add('event-message');
        message.content = message.fromName + ' 上线~!';
    } else if (message.messageTypeId === 3) {
        messageElement.classList.add('event-message');
        message.content = message.fromName + ' 离线了!';
    } else {
        messageElement.classList.add('chat-message');

        var avatarElement = document.createElement('i');
        var avatarText = document.createTextNode(message.fromName[0]);
        avatarElement.appendChild(avatarText);
        avatarElement.style['background-color'] = getAvatarColor(message.fromName);

        messageElement.appendChild(avatarElement);

        var usernameElement = document.createElement('span');
        var usernameText = document.createTextNode(message.fromName);
        usernameElement.appendChild(usernameText);
        messageElement.appendChild(usernameElement);
    }

    var textElement = document.createElement('p');
    var messageText = document.createTextNode('消息：'+message.content);
    textElement.appendChild(messageText);

    messageElement.appendChild(textElement);

    messageArea.appendChild(messageElement);
    messageArea.scrollTop = messageArea.scrollHeight;
}


function getAvatarColor(messageSender) {
    var hash = 0;
    for (var i = 0; i < messageSender.length; i++) {
        hash = 31 * hash + messageSender.charCodeAt(i);
    }
    var index = Math.abs(hash % colors.length);
    return colors[index];
}
usernameForm.addEventListener('submit', connect, true)
messageForm.addEventListener('submit', sendMessage, true)
